const connection = require('../app/database');

class MusicService {

  // 创建一个音乐
  async create(userId, musicId, name, artist, cover, url) {
    try {
      const statement = `INSERT INTO music (user_id, music_id, music_name, music_artist, music_cover, music_url) VALUES (?, ?, ?, ?, ?, ?)`;
      const result = await connection.execute(statement, [userId, musicId, name, artist, cover, url]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个音乐
  async remove(musicId, userId) {
    try {
      const statement = `DELETE FROM music WHERE id = ? AND user_id = ?`;
      const result = await connection.execute(statement, [musicId, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改一个音乐
  async update(userId, m_id, musicId, name, artist, cover, url) {
    try {
      const statement = `UPDATE music SET music_id = ?, music_name = ?, music_artist = ?, music_cover = ?, music_url = ? WHERE id = ? AND user_id = ?`;
      const result = await connection.execute(statement, [musicId, name, artist, cover, url, m_id, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取音乐详情
  async getMusicById(m_id, userId) {
    try {
      const statement = `
                        SELECT 
                          id m_id,
                          user_id userId,
                          music_id musicId,
                          music_name name,
                          music_artist artist,
                          music_cover cover,
                          music_url url,
                          createAt createTime
                        FROM music
                        WHERE id = ? AND user_id = ?`;
      const [result] = await connection.execute(statement, [m_id, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取音乐列表
  async list(userId) {
    try {
      const statement = `
                  SELECT 
                    id 'key',
                    user_id userId,
                    music_id musicId,
                    music_name name,
                    music_artist artist,
                    music_cover cover,
                    music_url url,
                    createAt createTime
                  FROM music
                  WHERE user_id = ?
                `;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 判断音乐是否存在
  async existMusic(musicId, userId) {
    try {
      const statement = `SELECT id FROM music WHERE music_id = ? AND user_id = ?`;
      const result = await connection.execute(statement, [musicId, userId]);
      return result[0];
    } catch (error) {
      console.log(error)
    }
  }
}

module.exports = new MusicService();
